package sma;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import model.ApplicationModel;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.Runtime;
import jade.wrapper.AgentContainer;
import jade.wrapper.StaleProxyException;

public class AgentController {

	static final Logger log = LoggerFactory
			.getLogger(AgentController.class);

	private final ApplicationModel applicationModel;

	public AgentController(ApplicationModel applicationModel) {
		super();
		this.applicationModel = applicationModel;
	}

	public void initAgent() {
		log.info("initing agents ...");
		Runtime rt = Runtime.instance();
		Profile p = null;
		try {
			p = new ProfileImpl("agent.properties");
			AgentContainer mc = rt.createMainContainer(p);
			createAndStartAgent(mc, "MTStatechartAgent", "sma.agent.MTStatechartAgent",
					applicationModel);
		} catch (Exception ex) {
			log.error("initing agents FAILED");
			ex.printStackTrace();
		}
		log.info("initing agents DONE");
	}

	private void createAndStartAgent(AgentContainer mc, String name,
			String clazz, Object... objs) throws StaleProxyException {
		jade.wrapper.AgentController ac = mc.createNewAgent(name, clazz, objs);
		ac.start();
	}

	@SuppressWarnings("unused")
	private static void createAndStartAgent(AgentContainer mc, String name,
			String clazz) throws StaleProxyException {
		jade.wrapper.AgentController ac = mc.createNewAgent(name, clazz,
				new Object[] { 0 });
		ac.start();
	}

}
